package com.learning.optimize.jdk.regex;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class MultiFormatMatcher {
    private List<FormatPattern> patterns;

    // 定义格式模式类
    private static class FormatPattern {
        String name;
        Pattern pattern;
        List<String> fieldNames;

        FormatPattern(String name, String regex, List<String> fieldNames) {
            this.name = name;
            pattern = Pattern.compile(regex);
            this.fieldNames = fieldNames;
        }
    }

    public MultiFormatMatcher() {
        patterns = new ArrayList<>();
        initializePatterns();
    }

    private void initializePatterns() {
        // 1. 基础信息格式: 男15年交清50
        patterns.add(new FormatPattern(
                "basic_info",
                "^(男|女)(\\d+)年交清(\\d+)$",
                Arrays.asList("gender", "years", "age")
        ));

        // 2. 多字段组合格式: [dlz_sex][dlz_jfqj][dlz_age]
        patterns.add(new FormatPattern(
                "multi_field",
                "^((?:\\[[^\\]]+\\])+)$",
                Arrays.asList("fields") // 后续会解析具体字段
        ));

        // 3. 地区+类型格式: [yywd_city][yywd_area]的[YYWD]
        patterns.add(new FormatPattern(
                "area_type",
                "^\\[([^\\]]+)\\]\\[([^\\]]+)\\]的\\[([^\\]]+)\\]$",
                Arrays.asList("city", "area", "type")
        ));

        // 4. 详细查询格式: [yywd_province][yywd_city]的[YYWD](地址|在哪|...)
        String querySuffix = "(地址|在哪|在哪儿|在哪里|在什么地方|位置|位置在哪|地址在哪|信息|具体地址|具体位置)";
        patterns.add(new FormatPattern(
                "detailed_query",
                "^\\[([^\\]]+)\\]\\[([^\\]]+)\\]的\\[([^\\]]+)\\]" + querySuffix + "$",
                Arrays.asList("province", "city", "type", "query_type")
        ));

        // 5. 职业代码格式: [zhiyecc12]的职业代码
        patterns.add(new FormatPattern(
                "career_code",
                "^\\[([^\\]]+)\\]的职业代码$",
                Arrays.asList("career_prefix")
        ));

        // 6. 银行账户格式: 实时交费能用[bank]的账户吗
        patterns.add(new FormatPattern(
                "bank_account",
                "^实时交费能用\\[([^\\]]+)\\]的账户吗$",
                Arrays.asList("bank")
        ));

        // 7. 职业分类查询格式: 查一下[zycxcctp]职业分类情况
        patterns.add(new FormatPattern(
                "career_query",
                "^查一下\\[([^\\]]+)\\]职业分类情况$",
                Arrays.asList("career_type")
        ));
    }

    /**
     * 匹配输入字符串并返回解析结果
     */
    public Optional<MatchResult> match(String input) {
        for (FormatPattern format : patterns) {
            Matcher matcher = format.pattern.matcher(input);
            if (matcher.matches()) {
                return Optional.of(parseMatchResult(format, matcher, input));
            }
        }
        return Optional.empty();
    }

    /**
     * 解析匹配结果
     */
    private MatchResult parseMatchResult(FormatPattern format, Matcher matcher, String input) {
        Map<String, String> fields = new HashMap<>();

        // 特殊处理多字段组合格式
        if ("multi_field".equals(format.name)) {
            String combinedFields = matcher.group(1);
            List<String> extractedFields = extractBracketFields(combinedFields);
            fields.put("field_count", String.valueOf(extractedFields.size()));
            for (int i = 0; i < extractedFields.size(); i++) {
                fields.put("field_" + (i + 1), extractedFields.get(i));
            }
        } else {
            // 普通格式，按组提取
            for (int i = 0; i < format.fieldNames.size(); i++) {
                fields.put(format.fieldNames.get(i), matcher.group(i + 1));
            }
        }

        return new MatchResult(format.name, input, fields);
    }

    /**
     * 从多字段组合中提取各个字段
     */
    private List<String> extractBracketFields(String input) {
        List<String> fields = new ArrayList<>();
        Pattern fieldPattern = Pattern.compile("\\[([^\\]]+)\\]");
        Matcher matcher = fieldPattern.matcher(input);

        while (matcher.find()) {
            fields.add(matcher.group(1));
        }
        return fields;
    }

    /**
     * 批量匹配
     */
    public List<MatchResult> matchAll(List<String> inputs) {
        return inputs.stream()
                .map(this::match)
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    /**
     * 匹配结果类
     */
    public static class MatchResult {
        private final String formatType;
        private final String originalInput;
        private final Map<String, String> fields;

        public MatchResult(String formatType, String originalInput, Map<String, String> fields) {
            this.formatType = formatType;
            this.originalInput = originalInput;
            this.fields = Collections.unmodifiableMap(fields);
        }

        // Getters
        public String getFormatType() {
            return formatType;
        }

        public String getOriginalInput() {
            return originalInput;
        }

        public Map<String, String> getFields() {
            return fields;
        }

        @Override
        public String toString() {
            return String.format("MatchResult{format='%s', fields=%s}", formatType, fields);
        }
    }

    public static void main(String[] args) {
        MultiFormatMatcher matcher = new MultiFormatMatcher();

        // 测试所有格式
        List<String> testCases = Arrays.asList(
                "男15年交清50",                          // 基础信息格式
                "[dlz_sex][dlz_jfqj][dlz_age]",          // 多字段组合格式
                "[yywd_city][yywd_area]的[YYWD]",        // 地区+类型格式
                "[yywd_province][yywd_city]的[YYWD]地址", // 详细查询格式
                "[zhiyecc12]的职业代码",                  // 职业代码格式
                "实时交费能用[bank]的账户吗",              // 银行账户格式
                "查一下[zycxcctp]职业分类情况",           // 职业分类查询格式
                "[invalid]格式"                         // 无效格式
        );

        System.out.println("=== 格式匹配测试 ===");
        for (String testCase : testCases) {
            Optional<MatchResult> result = matcher.match(testCase);
            if (result.isPresent()) {
                System.out.println("✓ " + testCase + " -> " + result.get());
            } else {
                System.out.println("✗ " + testCase + " -> 不匹配");
            }
        }

        System.out.println("\n=== 批量匹配结果 ===");
        List<MatchResult> batchResults = matcher.matchAll(testCases);
        batchResults.forEach(System.out::println);

        // 演示具体字段提取
        System.out.println("\n=== 字段提取演示 ===");
        String multiField = "[dlz_sex][dlz_jfqj][dlz_age]";
        matcher.match(multiField).ifPresent(result -> {
            System.out.println("多字段解析: " + multiField);
            result.getFields().forEach((key, value) ->
                    System.out.println("  " + key + ": " + value));
        });
    }
}